<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告框区域 -->
      <el-alert title="注意：只允许为第三级别分类设置相关参数" type="warning" show-icon></el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="cateListChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数部分 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="warning"
            size="mini"
            plain
            :disabled="isBtnDisabled"
            @click="addParamVisible=true"
          >动态参数</el-button>
          <!-- 静态属性部分的数据 -->
          <el-table style="width: 100%" :data="manyTabData" border stripe>
            <!-- 扩展列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable>{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="动态参数"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  plain
                  size="mini"
                  type="warning"
                  icon="el-icon-edit"
                  @click="editParamsHandle(scope.row)"
                >编辑</el-button>
                <el-button
                  plain
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParamsHandle(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性部分 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="warning"
            size="mini"
            plain
            :disabled="isBtnDisabled"
            @click="addParamVisible=true"
          >静态属性</el-button>
          <!-- 静态属性部分的数据 -->
          <el-table style="width: 100%" :data="onlyTabData" border stripe>
            <!-- 扩展列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable>{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="静态属性"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  plain
                  size="mini"
                  type="warning"
                  icon="el-icon-edit"
                  @click="editParamsHandle(scope.row)"
                >编辑</el-button>
                <el-button
                  plain
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParamsHandle(scope.row.attr_id)"
                >删除</el-button>
                <!-- scope.row.attr_id注意这里的写法，如果这里只写一个scope.row后面的参数获取Id记得获取attr_id不然会报错 -->
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加分类参数的对话框 -->
    <el-dialog
      :title="'添加'+textTitle"
      :visible.sync="addParamVisible"
      width="30%"
      @close="handleAddClose"
    >
      <el-form :model="addParams" :rules="addParamsRules" ref="addParamsRef" label-width="100px">
        <el-form-item label="活动名称" prop="attr_name">
          <el-input v-model="addParams.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSureBtn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类参数的对话框 -->
    <el-dialog
      :title="'编辑'+textTitle"
      :visible.sync="editParamVisible"
      width="30%"
      @close="handleEditClose"
    >
      <el-form :model="editParams" :rules="editParamsRules" ref="editParamsRef" label-width="100px">
        <el-form-item label="活动名称" prop="attr_name">
          <el-input v-model="editParams.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSureBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      // 输入框的数据
      inputValue: [],
      // 控制扩展区域的输入框可见性
      inputVisible: false,
      // 存储的是编辑分类的验证规则
      editParamsRules: {
        attr_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      },
      // 存储的是编辑分类的数据
      editParams: {
        attr_name: ''
      },
      // 控制的是编辑参数弹框的可见性
      editParamVisible: false,
      // 存储的是添加分类的验证规则
      addParamsRules: {
        attr_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      },
      // 存储的是添加分类的数据
      addParams: {
        attr_name: ''
      },
      // 控制的是添加参数弹框的可见性
      addParamVisible: false,
      onlyTabData: [],
      manyTabData: [],
      // 被选择的分类数据数组(就是所有选中数据的id的数组集合)
      selectedCateKeys: [],
      // 所有的数据
      cateList: [],
      // 一些配置项
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 默认选中Tab的类名
      activeName: 'many'
    }
  },
  methods: {
    // 点击扩展区按钮的事件
    showInput() {
      this.inputVisible = true
    },

    // 控制扩展区输入框的事件
    handleInputConfirm() {},

    // 点击删除按钮触发的事件
    async deleteParamsHandle(id) {
      const messageDelete = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (messageDelete !== 'confirm') {
        // 说明用户取消了删除
        return this.$message.info('您取消了删除')
      }
      const { data: res } = await this.$http.delete(`categories/${this.isId}/attributes/${id}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getTabList()
    },

    // 当点击编辑按钮触发的事件
    async editParamsHandle(idList) {
      // 点击编辑按钮先发送请求获取到当前行的数据
      const { data: res } = await this.$http.get(`categories/${this.isId}/attributes/${idList.attr_id}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.editParams = res.data
      this.editParamVisible = true
    },

    // 处理的是编辑弹框的关闭事件
    handleEditClose() {
      this.$refs.editParamsRef.resetFields()
    },

    // 确认编辑参数的事件
    editSureBtn() {
      // 先对输入框进行校验，然后发送请求
      this.$refs.editParamsRef.validate(async valid => {
        const { data: res } = await this.$http.put(`categories/${this.isId}/attributes/${this.editParams.attr_id}`, {
          attr_name: this.editParams.attr_name,
          attr_sel: this.editParams.attr_sel
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getTabList()
        this.editParamVisible = false
      })
    },

    // 点击确认添加按钮时发送请求添加数据
    addSureBtn() {
      // 店家添加按钮先进行表单数据的校验，然后成功发送请求
      // 并且关闭弹窗
      // 重新渲染表格数据
      this.$refs.addParamsRef.validate(async valid => {
        const { data: res } = await this.$http.post(`categories/${this.isId}/attributes`, {
          attr_name: this.addParams.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.addParamVisible = false
        this.getTabList()
        console.log(res)
      })
    },

    // 当关闭添加对话框时 要将表单数据进行重置
    handleAddClose() {
      this.$refs.addParamsRef.resetFields()
    },

    // 获取tab的数据
    async getTabList() {
      // 先判断是否选中三级目录，如果选中的是三级目录，发送请求
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        return
      }
      // 当数据长度为三可以发送请求时
      const { data: res } = await this.$http.get(`categories/${this.isId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
      })
      // 对返回的数据进行处理(返回的数据是动态数据和静态属性的集合)
      if (this.activeName === 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },

    // 当tab被点击触发
    handleTabClick() {
      this.getTabList()
    },

    // 级连选择器数据改变
    cateListChange() {
      // 在这里调用获取数据的方法
      this.getTabList()
    },

    // 获取所有的分类商品
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 控制的是标题元素
    textTitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
    // 控制的是按钮是否被禁用
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 需要获取到id，所以获取到id,只返回三级id
    isId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      } else {
        return null
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px;
  .el-cascader {
    margin-left: 20px;
  }
}
.input-new-tag {
  width: 150px;
}
</style>
